﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using libDAL;
using clsEmployeeList.BUS;
using System.IO;
using Telerik.WinControls.Data;
using Telerik.WinControls.UI;
using libAuditTrail;
using libDAL;


namespace clsEmployeeList.Forms
{
    public partial class frmUserProfile : Telerik.WinControls.UI.RadForm, IDisposable
    {
        private frmUserProfile frmHolder;
        private clsEmpListInterface _BUS;
        private bool bolLoaded = false;
        private string strEmployeeID = string.Empty;
        private bool bolCancel = false;
        private int intCol = 0;
        private string strSelectionType = string.Empty;
        private cls_DAL _DAL;

        public void set_frmHolder(ref frmUserProfile frmHold, cls_DAL DAL)
        {
            frmHolder = frmHold;
            _DAL = DAL;
        }

        ~frmUserProfile()
        { }

        public frmUserProfile()
        {
            InitializeComponent();
        }

        private void set_BackStage()
        {
            RadPageViewBackstageElement backStageElement = rpvUserProfile.ViewElement as RadPageViewBackstageElement;
            StripViewItemContainer itemContainer = backStageElement.ItemContainer as StripViewItemContainer;
            StripViewItemLayout itemLayout = backStageElement.ItemContainer.ItemLayout as StripViewItemLayout;

            itemContainer.MinSize = new Size(80, 0);
        }

        private void frmUserProfile_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'actcomregDataSet.mfcomprofile' table. You can move, or remove it, as needed.

            this.FormBorderStyle = FormBorderStyle.None;
            this.ControlBox = false;
            this.MinimizeBox = false;
            this.MaximizeBox = false;
            
            this.mfcomprofileTableAdapter.Fill(this.actcomregDataSet.mfcomprofile);

            dgvEmployeeList.SelectionChanged -= dgvEmployeeList_SelectionChanged;
            
            _BUS = new clsEmpListInterface();
            _BUS.set_UnTagAllInUse("UserID");
                
            set_LoadEmployeeList();

            dgvEmployeeList.SelectionChanged += dgvEmployeeList_SelectionChanged;
            

            bolLoaded = true;

            clsGenFunction.set_BackStage(ref rpvUserProfile); 


        }

        private void set_LoadEmployeeList()
        {
            try
            {
                if (_BUS.set_EmployeeList() == true)
                {
                    if (set_LoadEmployeeListToGrid(_BUS.get_AllEmployees) == true)
                    {
                        this.bolLoaded = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " libEmployeeList_frmEmployeeProfile_set_LoadEmployeeList");
            }
        }

        private Boolean set_LoadEmployeeListToGrid(DataRow[] drList)
        {
            bool bolStatus = false;
            try
            {
                int intIndexx = 0;
                if (dgvEmployeeList.Rows.Count > 0)
                {
                    dgvEmployeeList.Rows.Clear();
                }

                GridViewDataRowInfo rowInfo = new GridViewDataRowInfo(this.dgvEmployeeList.MasterView);
               
                if (Convert.ToInt32(mskSeachProfiles.Value) > 0)
                {
                    if (drList.Length < Convert.ToInt32(mskSeachProfiles.Value))
                    {
                        intIndexx = drList.Length;
                    }
                    else
                    {
                        intIndexx = Convert.ToInt32(mskSeachProfiles.Value);
                    }

                    for (int intIndex = 0; intIndex < intIndexx; intIndex++)
                    {
                        rowInfo = new GridViewDataRowInfo(this.dgvEmployeeList.MasterView);
                        for (int intCol = 0; intCol < 8; intCol++)
                        {
                            rowInfo.Cells[intCol].Value = drList[intIndex][intCol];
                        }
                        dgvEmployeeList.Rows.Add(rowInfo);
                        bolStatus = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "libEmployeeList_frmEmployeeProfile_set_LoadEmployeeListToGrid");
            }
            return bolStatus;
        }

        private void btnPassword_Click(object sender, EventArgs e)
        {
            frmPasswordSetup pass = new frmPasswordSetup();

            Point p = gbCredentials.PointToScreen(btnPassword.Location);


            pass.set_NewLocation(p.X, p.Y + btnPassword.Height);  
            pass.ShowDialog();
        }

        private void btnDBAccess_Click(object sender, EventArgs e)
        {
            frmDBLocationsAccess acc = new frmDBLocationsAccess();
            Point p = gbCredentials.PointToScreen(btnDBAccess.Location);
            acc.set_NewLocation(p.X, p.Y + btnDBAccess.Height);  
            acc.set_SetTypeAccessOrLevel("Access");
            acc.ShowDialog();
        }

        private void set_UntagUser()
        {
            if (_BUS.getset_EmployeeID.Trim() != string.Empty)
            {
                _BUS.set_UnTagAllInUse("UserID");
            }
        }

        private void set_EmployeeTextFieldCredentials()
        {
            try
            {
                string strEmployeeID = string.Empty;
                strEmployeeID = dgvEmployeeList.CurrentRow.Cells["EmployeeID"].Value.ToString().Trim();

                set_UntagUser();

                if (_BUS.get_CheckEmployeeOnUse(strEmployeeID, "UserID") == false)
                {
                    DataRow[] drCredentials = _BUS.get_EmployeeCredentials(strEmployeeID);


                    if (drCredentials.Length > 0)
                    {
                        _BUS.set_AppListLoadActual(strEmployeeID);
                        get_CheckAppListLoaded();
                        _BUS.getset_EmployeeID = string.Empty;
                        txtUserName.Text = _BUS.getset_strUserName;
                        txtFirstName.Text = _BUS.getset_FirstName;
                        txtLastName.Text = _BUS.getset_LastName;
                        txtMI.Text = _BUS.getset_MiddleInitial;
                        cboHQBranch.Text = _BUS.getset_Branch;
                        cboDesignation.Text = _BUS.getset_Designation;
                        _BUS.getset_EmployeeID = strEmployeeID;
                        set_rboAccountStatus();
                        _BUS.get_TagUnTagOnUse(1, "UserID", strEmployeeID);
                        set_LoadAppReportList2("Program", string.Empty);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " libEmployeeList_frmEmployeeProfile_set_EmployeeTextFieldCredentials");
            }
        }

        private bool get_CheckAppListLoaded()
        {
            bool bolStatus = false;
            if (_BUS.get_checkApplistExists() == false)
            {
                bolStatus = _BUS.get_EmployeeAccessList(_BUS.getset_EmployeeID);
            }
            else
            {
                bolStatus = true;
            }

            return bolStatus;
        }

        private DataRow[] get_AppReportList(string strType, string strSearch)
        {
            DataRow[] drAccess = { };
            try
            {
                if (getset_SearchTypeApplicationReport.Trim() == string.Empty)
                {
                    drAccess = _BUS.get_AccessTypeReportProgram(strType);
                }
                else
                {
                    drAccess = _BUS.get_AccessTypeReportProgram(strType, strSearch);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " libEmployeeList_Forms_frmUserProfile_get_AppReportList"); 
            }
            return drAccess;
        }

        private void set_LoadAppReportList2(string strType, string strSearch)
        {
            try
            {
                GridViewDataRowInfo rowInfo = new GridViewDataRowInfo(this.dgvApplicationList.MasterView);
                int intIndexx = 0;
                DataRow[] drAccess;

               
                    if (dgvApplicationList.Rows.Count > 0)
                    {
                        dgvApplicationList.Rows.Clear();
                    }

                    drAccess = get_AppReportList(strType, strSearch);
                    if (drAccess.Length < Convert.ToInt32(mskSearchAccess.Value))
                    {
                        intIndexx = drAccess.Length;
                    }
                    else
                    {
                        intIndexx =  Convert.ToInt32(mskSearchAccess.Value);
                    }
                    if (intIndexx > 0)
                    {
                        for (int intIndex = 0; intIndex < intIndexx; intIndex++)
                        {
                            rowInfo = new GridViewDataRowInfo(this.dgvApplicationList.MasterView);

                            rowInfo.Cells[0].Value = drAccess[intIndex]["mdModulename"].ToString().Trim();
                            rowInfo.Cells[1].Value = drAccess[intIndex]["mdModuleDescription"].ToString().Trim();
                            rowInfo.Cells[3].Value = drAccess[intIndex]["EmployeeID_ar"].ToString().Trim();
                            rowInfo.Cells[4].Value = drAccess[intIndex]["EmployeeAccessID"].ToString().Trim();
                            rowInfo.Cells[5].Value = drAccess[intIndex]["ModuleID"].ToString().Trim();
                            rowInfo.Cells[6].Value = drAccess[intIndex]["LastMOdifiedBy_ar"].ToString().Trim();

                            #region Date
                            if (drAccess[intIndex].IsNull("DateTimeInserted") == true || drAccess[intIndex]["DateTimeInserted"].ToString().Trim() == string.Empty)
                            {
                                rowInfo.Cells[7].Value = DBNull.Value;
                            }
                            else
                            {
                                rowInfo.Cells[7].Value = drAccess[intIndex]["DateTimeInserted"].ToString().Trim();
                            }

                            if (drAccess[intIndex].IsNull("DateTimeUpdated_ar") == true || drAccess[intIndex]["DateTimeUpdated_ar"].ToString().Trim() == string.Empty)
                            {
                                rowInfo.Cells[8].Value = DBNull.Value;
                            }
                            else
                            {
                                rowInfo.Cells[8].Value = drAccess[intIndex]["DateTimeUpdated_ar"].ToString().Trim();
                            }
                            #endregion

                            rowInfo.Cells[9].Value = drAccess[intIndex]["HostNameIPAddress_ar"].ToString().Trim();
                            dgvApplicationList.Rows.Add(rowInfo);
                        }
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " libEmployeeList_Forms_frmUserProfile_set_LoadAppReportList2");
            }
        }

        private void set_rboAccountStatus()
        {
            if (_BUS.getset_UserAccountStatus == 0)
            {
                rboInactive.IsChecked = true;
            }
            else
            {
                rboInactive.IsChecked = false;
            }

            if (_BUS.getset_UserAccountStatus == 1)
            {

                rboActive.IsChecked = true;
            }
            else
            {
                rboActive.IsChecked = false;
            }

        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            try
            {
                set_LoadEmployeeListToGrid(_BUS.get_getSpecificEmployees(txtSearch.Text.Trim()));
            }
            catch (Exception ex)
            {
            }
        }

        private void dgvEmployeeList_SelectionChanged(object sender, EventArgs e)
        {
            if (bolLoaded == true)
            {
                set_EmployeeTextFieldCredentials();
            }
        }

        private void rboApplications_ToggleStateChanged(object sender, StateChangedEventArgs args)
        {
            if (rboApplications.IsChecked == true)
            {
                getset_SearchTypeApplicationReport = "Program";

                try
                {
                    set_LoadAppReportList2("Program", string.Empty);
                }
                catch (Exception ex)
                {
                }

            }
            else if (rboReports.IsChecked == true)
            {
                getset_SearchTypeApplicationReport = "Report";
                set_LoadAppReportList2("Report", string.Empty);
            }
        }

        private string getset_SearchTypeApplicationReport
        {
            get
            {
                return strSelectionType;
            }
            set
            {
                strSelectionType = value;
            }
        }

        private void radTextBoxControl1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (rboReports.IsChecked == true)
            {
                set_LoadAppReportList2("Report", txtAppSearch.Text.Trim());
            }
            else if (rboApplications.IsChecked == true)
            {
                set_LoadAppReportList2("Program", txtAppSearch.Text.Trim());
            }
        }

        private string get_NewEmployeeID()
        {
            string strIDPart = DateTime.Now.ToString("MdyyHmss");

            strEmployeeID = txtFirstName.Text.Trim().Substring(0, 3) +
                            txtLastName.Text.Trim().Substring(0, 3) +
                            cboHQBranch.Text.Trim().Substring(0, 4);
            return strEmployeeID;
        }
        
        private Boolean get_ValidateEmployeeProfile()
        {

            bool bolStatus = false;
            try
            {
                bool bolLastName = true;
                bool bolfirstName = true;
                bool bolHQBranch = true;

                if (txtFirstName.Text.Trim() == string.Empty)
                {
                    epFirstName.SetError(txtFirstName, "epLastName");
                    bolfirstName = false;
                }
                else
                {
                    epFirstName.Clear();
                    bolfirstName = true;
                }


                if (txtLastName.Text.Trim() == string.Empty)
                {
                    epLastName.SetError(txtLastName, "Field Empty.");
                    bolLastName = false;
                }
                else
                {
                    epLastName.Clear();
                    bolLastName = true;
                }

                if (cboHQBranch.Text.Trim() == string.Empty)
                {
                    epHQBranch.SetError(cboHQBranch, "Field Empty.");
                    bolHQBranch = false;
                }
                else
                {
                    epHQBranch.Clear();
                    bolHQBranch = true;
                }

                if (bolfirstName == false || bolLastName == false || bolHQBranch == false)
                {
                    bolStatus = false;
                }
                else
                {
                    bolStatus = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " libEmployeeList_frmEmployeeProfile_get_ValidateEmployeeProfile");
            }
            return bolStatus;
        }

        private int get_EmployeeAccountStatus()
        {
            int intStatus = 0;
            try
            {
                if (rboInactive.IsChecked == true)
                {
                    intStatus = 0;
                }
                else if (rboActive.IsChecked == true)
                {

                    intStatus = 1;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " get_EmployeeAccountStatus");
            }
            return intStatus;
        }

        private string get_EmployeeID()
        {
            string strTempID = string.Empty;
            if (_BUS.getset_EmployeeID.Trim() == string.Empty)
            {
                strTempID = get_NewEmployeeID();
            }
            else
            {
                strTempID = _BUS.getset_EmployeeID;
            }
            return strTempID;
        }

        private string get_CurrentEmployeeRecord()
        {
            string strRecord = _BUS.getset_EmployeeID + _BUS.getset_FirstName + _BUS.getset_LastName + _BUS.getset_MiddleInitial +
                               _BUS.getset_Designation + _BUS.getset_Branch + _BUS.getset_strUserName + _BUS.getset_UserAccountStatus;
            return strRecord;
        }

        private string get_NewEmployeeRecord()
        {
            string strRecord = txtFirstName.Text.Trim() + txtLastName.Text.Trim() + txtMI.Text.Trim() + 
                               cboDesignation.Text.Trim() + cboHQBranch.Text.Trim() + txtUserName.Text.Trim();

            return strRecord;
        
        }

        private void cbbSave_Click(object sender, EventArgs e)
        {
            try
            {
                string strEmployeeID = string.Empty;

                if (get_ValidateEmployeeProfile() == true)
                {
                   #region Insert Update
                        if (_BUS.set_InsertUpdateRecordsUserProfile(get_EmployeeID(), txtFirstName.Text.Trim(), txtLastName.Text.Trim(),
                                                                    txtMI.Text.Trim(), cboDesignation.Text.Trim(),"0",
                                                                    "", cboHQBranch.Text.Trim(), "lastModifiedby", txtUserName.Text.Trim(), get_EmployeeAccountStatus()) == true)
                        {

                            using (clsInsertAuditTrail AuditTrail = new clsInsertAuditTrail())
                            {
                                AuditTrail.set_AuditTrailRecord(get_EmployeeID(), this.Text,
                                                                "Insert or Update of user record ",
                                                                get_CurrentEmployeeRecord(),
                                                                get_NewEmployeeRecord(),
                                                                _BUS.getset_Branch);

                            }

                                dgvEmployeeList.SelectionChanged -= dgvEmployeeList_SelectionChanged;
                                set_LoadEmployeeList();
                                dgvEmployeeList.ClearSelection();
                                set_ClearEntryFields();
                                set_UntagUser();
                                set_ClearUserProfile();
                                _BUS.getset_EmployeeID = string.Empty;
                                dgvEmployeeList.SelectionChanged += dgvEmployeeList_SelectionChanged;
                        }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " libEmployeeList_frmEmployeeProfile_tsbSave_Click");
            }
        }

        private void set_ClearEntryFields()
        {
            txtFirstName.Text = string.Empty;
            txtLastName.Text = string.Empty;
            txtMI.Text = string.Empty;
            txtUserName.Text = string.Empty;
            cboDesignation.SelectedIndex = 0;
            cboHQBranch.SelectedIndex = 0;
        }

        private void btnLevel_Click(object sender, EventArgs e)
        {
            try
            {
                frmDBLocationsAccess acc = new frmDBLocationsAccess();
                Point p = gbCredentials.PointToScreen(btnLevel.Location);
                acc.set_NewLocation(p.X, p.Y + btnLevel.Height);
                acc.set_SetTypeAccessOrLevel("Access");
                acc.set_SetTypeAccessOrLevel("Level");
                acc.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " btnLevel_Click");
            }
        }

        private void cbbCancel_Click(object sender, EventArgs e)
        {
            try
            {
                dgvEmployeeList.SelectionChanged -= dgvEmployeeList_SelectionChanged;
                dgvApplicationList.Rows.Clear();
                _BUS.set_UnTagAllInUse("UserID");
                set_clearErrorProviders();
                set_ClearEntryFields();
                set_ClearUserProfile();
                set_ClearUserProfile();
                rpvUserProfile.TabIndex = 0;
                set_LoadEmployeeList();
                dgvEmployeeList.ClearSelection();
                dgvEmployeeList.SelectionChanged += dgvEmployeeList_SelectionChanged;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " cbbCancel_Click");
            }
        }

        private void set_clearErrorProviders()
        {
            epFirstName.Clear();
            epHQBranch.Clear();
            epLastName.Clear();
            epOldPassword.Clear();
            epRePassword.Clear();
            epUserLevel.Clear();
            epUserName.Clear();
        }

        private void set_ClearUserProfile()
        {
            _BUS.getset_FirstName = string.Empty;
            _BUS.getset_intUserLevel = 0;
            _BUS.getset_LastName = string.Empty;
            _BUS.getset_MiddleInitial = string.Empty;
            _BUS.getset_strPassword = string.Empty;
            _BUS.getset_strUserName = string.Empty;
            _BUS.getset_EmployeeID = string.Empty;
            _BUS.getset_Designation = string.Empty;
            _BUS.getset_Branch = string.Empty;
            _BUS.getset_UserAccountStatus = 0;
        }

        private bool get_SelectedStatus()
        {
            bool bolStatus = false;
            try
            {
                int intSelectedRows = dgvEmployeeList.SelectedRows.Count;
                if (intSelectedRows >= 1)
                {
                    bolStatus = true;
                }
                else
                {
                    MessageBox.Show("Please select specific employee to display other properties.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " libEmployeeList_Forms_frmUserProfile_get_SelectedStatus"); 
            }
            return bolStatus;
        }

        private void cbbDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (get_SelectedStatus() == true)
                {
                    frmPasswordValidationWithRemarks frmPEntry = new frmPasswordValidationWithRemarks();

                    DialogResult dgResult = frmPEntry.ShowDialog();
                    if (dgResult == DialogResult.OK)
                    {
                        if (_BUS.set_DeleteRecord(_BUS.getset_EmployeeID) == true)
                        {
                            using (clsInsertAuditTrail AuditTrail = new clsInsertAuditTrail())
                            {
                                AuditTrail.set_AuditTrailRecord(_BUS.getset_EmployeeID, this.Text,
                                                                "Delete of user record ",
                                                                get_CurrentEmployeeRecord(),
                                                                "",
                                                                _BUS.getset_Branch);

                            }

                            set_LoadEmployeeList();
                            dgvEmployeeList.ClearSelection();
                            set_ClearEntryFields();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " libEmployeeList_Forms_frmUserProfile_cbbDelete_Click"); 
            }
        }

        private void dgvApplicationList_CommandCellClick(object sender, EventArgs e)
        {
            GridCellElement cellElement = this.dgvApplicationList.TableElement.GetCellElement(this.dgvApplicationList.CurrentRow, this.dgvApplicationList.CurrentColumn);

            if (cellElement != null)
            {
                Point cellLocation = this.dgvApplicationList.PointToScreen(cellElement.ControlBoundingRectangle.Location);
                frmApplicationAccessList x = new frmApplicationAccessList();

                x.setPoint(cellLocation.X, cellLocation.Y + dgvApplicationList.CurrentCell.Size.Height);
                x.ShowDialog();
            }  
        }

        private void dgvEmployeeList_CellClick(object sender, GridViewCellEventArgs e)
        {
            

          
        }

        private void dgvApplicationList_CellClick(object sender, GridViewCellEventArgs e)
        {
        }

        private void frmUserProfile_FormClosing(object sender, FormClosingEventArgs e)
        {
            set_UntagUser();
            _BUS.set_CleanMemory();
            frmHolder = null;
        }

        private void frmUserProfile_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmHolder = null;
        }


    }
}
